package com.ihr360.oneclick.filter;

import cn.irenshi.db.core.DBContextHolder;
import com.ihr360.commons.constant.Constants;
import com.ihr360.commons.entity.AuthUserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author tom
 */
@Component
public class AuthUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return AuthUserInfo.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String companyId = request.getParameter(Constants.Session.COMPANY_ID);
        String companyName = request.getParameter(Constants.Session.COMPANY_NAME);
        String userId = request.getParameter(Constants.Session.USER_ID);
        String mobileNo = request.getParameter(Constants.Session.MOBILE_NO);
        String staffId = request.getParameter(Constants.Session.STAFF_ID);
        // TODO 强制设置中文语言环境，后期迭代在考虑英文环境
        LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE);
        DBContextHolder.setSchema(companyId);
        if(StringUtils.isNotBlank(companyId)){
            return new AuthUserInfo(companyId,companyName, userId,null, mobileNo, staffId);
        }
        return null;
    }
}
